<?php
class orgChart {
    public $tree;
    public function __construct() {
        $this->GetData();
    }

    public function GetData() {
        //Get $user, $password and $database
        include 'dbConn.php';

        //Query database for employee records
        $con = mysql_connect($server, $user, $password);
        if (!$con) {
            die('Could not connect: ' . mysql_error());
        }
        @mysql_select_db($database) or die("Unable to select database " . $database . ".");

        $query = "SELECT emp.`emp_number` AS id, rt.`erep_sup_emp_number` AS manager, CONCAT(emp.`emp_lastname`,' ',emp.`emp_middle_name`,' ',emp.`emp_firstname`) AS name, cst.`title` AS department, jt.jobtit_name as title
            FROM `hs_hr_employee` AS emp LEFT JOIN `hs_hr_emp_reportto` AS rt ON emp.`emp_number`=rt.`erep_sub_emp_number`
            LEFT JOIN `hs_hr_job_title` AS jt ON emp.`job_title_code`=jt.`jobtit_code`
            LEFT JOIN `hs_hr_compstructtree` AS cst ON emp.`work_station`=cst.`id`
            WHERE emp.`emp_status` != 'EST000'";

        $result = mysql_query($query) or die('3. Error querying employee info.');
        mysql_close();
        $data = array();
        while ($item = mysql_fetch_array($result)) {
            $data[] = $item;
        }
        $this->tree = $data;
    }

    public function buildOrgTree(array &$elements, $parentId = null) {
        $branch = array();

        foreach ($elements as $element) {
            if ($element['manager'] == $parentId) {
                $children = self::buildOrgTree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[$element['id']] = $element;
                unset($elements[$element['id']]);
            }
        }
        return $branch;
    }

}

?>
